/**
 * 发送get请求
 * @param {string} url 请求地址
 * @param {object} params 请求参数
 * @param {string|undefined} type 返回的接口数据类型
 * @param {object} headers 自定义请求头
 * @returns Promise
 */
function get(url, params, type, headers={})
{
    // 过滤数据
    let temp = []
    for (let key in params)
    {
        temp.push(`${key}=${params[key]}`)
    }
    let paramsFilter = temp.join('&')

    // 返回promise对象
    const p = new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest 
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4)
            {
                if (xhr.status === 200)
                {
                    let res = xhr.responseText
                    // 判断json数据
                    if (type==='json') res = JSON.parse(res)
                    resolve(res) 
                } else {
                    reject(xhr.status) 
                }
            }
        }
        xhr.open('get', `${url}?${paramsFilter}`)
        for (let key in headers) 
        {
            xhr.setRequestHeader(key, headers[key])
        }
        xhr.send(null)
    })
    
    return p
}

/**
 * 发送post请求
 * @param {string} url     
 * @param {string} params  
 * @param {object} params  
 * @param {object} headers  
 * @param {string} dataType 
 * @returns Promise
 */
function post(url, params = {}, headers = {}, dataType = 'json'){
    return new Promise((resolve,reject)=>{
        const xhr = new XMLHttpRequest
        xhr.onreadystatechange = function() {
            if(xhr.readyState === 4){
                if(xhr.status === 200){
                    let res = xhr.responseText
                    switch (dataType) {
                        case 'json':
                            res = JSON.parse(res)
                            break;
                    
                        default:
                            break;
                }
                resolve(res)}
                else{
                    reject(xhr.status)
                }
            }
        }
        
        xhr.open('post', url)

        xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')

        for (let key in headers)
        {
            xhr.setRequestHeader(key, headers[key])
        }


        let paramsArr = []
        for (let key in params)
        {
            paramsArr.push(`${key}=${params[key]}`)
        }
        xhr.send(paramsArr.join('&'))
    })
}